package pers.jing.android.helper

import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import pers.jing.android.helper.db.Database
import pers.jing.android.helper.model.CODE_SUCCESS
import pers.jing.android.helper.model.CommandResult
import pers.jing.android.helper.model.DeviceInfo
import pers.jing.android.helper.model.STATE_FAILURE
import pers.jing.android.helper.model.STATE_SUCCESS
import java.util.Collections

/**
 * 设备管理
 */
class DeviceManager(val database: Database) {

    private val _deviceList = MutableStateFlow(Collections.emptyList<DeviceInfo>())

    /**
     * 加载设备
     */
    suspend fun loadDevices() {
        val path = database.getConfig(ANDROID_SDK_PATH)
        if (path == null) {
            _deviceList.update {
                emptyList<DeviceInfo>()
            }
        } else {
            val port = database.getConfig(ADB_PORT)?.toIntOrNull()?:5037
            _deviceList.update {
                println("get devices success")
                AndroidSdkTools.getDevices(path, port)
            }
        }
    }

    fun getStateFlowDevices(): StateFlow<List<DeviceInfo>> {
        return _deviceList.asStateFlow()
    }

    fun getDevices(): List<DeviceInfo> {
        return _deviceList.value
    }

    suspend fun install(serialId: String, apkPath: String): CommandResult {
        val path = database.getConfig(ANDROID_SDK_PATH)
        if (path != null) {
            return AndroidSdkTools.installApk(path,
                deviceSerialId = serialId,
                apkPath = apkPath)
        }
        return CommandResult(-1, error = listOf("请先安装Android SDK"))
    }

}